﻿using System.Security.Cryptography;
using System.Text;

namespace XieCan.Core.Security
{
  public class SecurityHelper
  {
    /// <summary>
    /// MD5 加密字符串
    /// </summary>
    /// <param name="str">源字符串</param>
    /// <param name="salt">盐值</param>
    /// <returns>加密后字符串</returns>
    public static string MD5Encoding(string str, string salt = "")
    {
      if (string.IsNullOrWhiteSpace(str))
      {
        return "";
      }

      string temp = string.IsNullOrWhiteSpace(salt) ? str : (str + "//" + salt);
      byte[] bs = Encoding.UTF8.GetBytes(temp);
      byte[] hs = MD5.HashData(bs);
      StringBuilder sb = new();
      foreach (byte b in hs)
      {
        // 以十六进制格式格式化
        sb.Append(b.ToString("x2"));
      }
      return sb.ToString();
    }
  }
}
